package com.gzhryc.weixin.gzh;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.weixin.api.DefaultApiResponse;
import com.gzhryc.weixin.gzh.models.AccessToken;
import com.gzhryc.weixin.gzh.msg.GetUserInfoResponse;
import com.gzhryc.weixin.gzh.msg.GetUserOpenidListResponse;
import com.gzhryc.weixin.gzh.msg.Oauth2AccessToken;
import com.gzhryc.weixin.gzh.msg.Oauth2WeixinUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 微信用户API
 * @author 张浩
 * @version 0.3.11
 */
public class WxUserApi extends AbsWeixinApi{

	private final static Logger log = Logger.getLogger(WxUserApi.class);

	public WxUserApi(AccessToken accessToken) {
		super(accessToken);
	}

	/**
	 * 获取用户的OPENID集合
	 * @param nextOpenid 	第一个拉取的OPENID，不填默认从头开始拉取
	 * @return
	 */
	public GetUserOpenidListResponse getUserOpenidList(String nextOpenid){
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			URIBuilder uriBuilder = new URIBuilder()
		        .setScheme("https")
		        .setHost("api.weixin.qq.com")
		        .setPath("/cgi-bin/user/get")
		        .setParameter("access_token",accessToken.getAccess_token());
			
			if(StringUtils.isNotBlank(nextOpenid)){
				uriBuilder.setParameter("next_openid",nextOpenid);
			}
			URI uri = uriBuilder.build();
			HttpGet httpget = new HttpGet(uri);
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
				if(isError(str)){
					accessToken.queuePut(JsonTools.fromJson(str, DefaultApiResponse.class));
				}else{
					return JsonTools.fromJson(str, GetUserOpenidListResponse.class);
				}
			}
		} catch(Exception e){
			log.error("getUserOpenidList error", e);
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	/**
	 * 根据用户OPENID获取用户信息，不能获取昵称和头像
	 * https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
	 * @param openid
	 * @return
	 */
	public GetUserInfoResponse getUserInfo(String openid){
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			URI uri = new URIBuilder()
		        .setScheme("https")
		        .setHost("api.weixin.qq.com")
		        .setPath("/cgi-bin/user/info")
		        .setParameter("access_token",accessToken.getAccess_token())
		        .setParameter("openid",openid)
		        .setParameter("lang","zh_CN")
		        .build();
			HttpGet httpget = new HttpGet(uri);
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
				log.debug(str);
				if(isError(str)){
					accessToken.queuePut(JsonTools.fromJson(str, DefaultApiResponse.class));
				}else{
					GetUserInfoResponse result = JsonTools.fromJson(str, GetUserInfoResponse.class);
					return result;
				}
			}
		} catch(Exception e){
			log.error("getUserInfo error", e);
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	/**
	 * 获取微信用户信息
	 * https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
	 * @param oauth2AccessToken
	 * @return
	 */
	public Oauth2WeixinUser getWeixinUser(Oauth2AccessToken oauth2AccessToken){
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			URI uri = new URIBuilder()
		        .setScheme("https")
		        .setHost("api.weixin.qq.com")
		        .setPath("/sns/userinfo")
		        .setParameter("access_token",oauth2AccessToken.getAccess_token())
		        .setParameter("openid",oauth2AccessToken.getOpenid())
		        .setParameter("lang","zh_CN")
		        .build();
			HttpGet httpget = new HttpGet(uri);
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
				if(isError(str)){
					accessToken.queuePut(JsonTools.fromJson(str, DefaultApiResponse.class));
				}else{
					return JsonTools.fromJson(str, Oauth2WeixinUser.class);
				}
			}
		} catch(Exception e){
			log.error(e.getMessage(), e);
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

}
